import type { CancellablePromise } from '@gnlab/utils'
import type { OrderedMap } from 'immutable'
import type { BaseContact } from '@/services/contacts'
import { makeContactId, ContactType } from '@/services/contacts'

export interface GroupContact extends BaseContact {
  type: ContactType.group
  created: number // 创建时间
  creatorWxid: string // 群主的 wxid
  isExternal: boolean // 是否是外部群
  isOwner: boolean // 是否是群主
  total: number // 群成员数量
}

// 仅保留必须字段的群联系人
export type BaseGroup = Pick<
  GroupContact,
  | 'type'
  | 'id'
  | 'conversationId'
  | 'ownerWxid'
  | 'userId'
  | 'name'
  | 'creatorWxid'
  | 'isExternal'
  | 'isOwner'
>

// 传入最基础的信息，生成一个临时的群联系人
export function makeGroupByBaseInfo(info: {
  conversationId: string
  ownerWxid: string
  isExternal: boolean
  creatorWxid: string
}): BaseGroup {
  const { conversationId, ownerWxid, isExternal, creatorWxid } = info
  return {
    type: ContactType.group,
    id: makeContactId(ownerWxid, conversationId),
    conversationId,
    ownerWxid,
    userId: conversationId,
    name: conversationId,
    creatorWxid,
    isExternal,
    isOwner: creatorWxid === ownerWxid,
  }
}

/**
 * 群联系人变动事件
 */
export enum GroupEventType {
  Created = 1, // 新群建立成功
}
export type GroupEvent = { type: GroupEventType.Created; contactId: string }

/**
 * 群额外信息
 */
export interface GroupExtra {
  describe: string // 群描述（可多行）
}

/**
 * 群静音信息
 */
export interface MuteGroup {
  id: number // 静音记录 ID
  wxid: string
  conversationId: string
}

/**
 * 群标签
 */
export interface GroupTag {
  id: number
  name: string
}

export interface BaseGroupSearchConditions {
  tagIds: number[]
  wxids?: string[]
}
export type GroupSearching =
  | (BaseGroupSearchConditions & { loading: CancellablePromise<unknown>; items: null })
  | (BaseGroupSearchConditions & { loading: null; items: OrderedMap<string, GroupContact> })
  | null
